package com.fingard.dsp.bank.directbank.ccblifeicbc02;

import java.util.Calendar;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * 批量代收付
 * 
 * 需求描述：
 * 		1、指令代码：PERDIS -- 批量代扣提交
 * 		2、指令代码：QPERDIS -- 批量代扣状态查询
 *      3、指令代码：PAYENT -- 支持单笔支付及批量支付
 * 		4、指令代码：QPAYENT -- 支持单笔支付及批量支付查询
 * @author Cruise
 * @date 2018/10/23
 */
public class CCBLifeICBC02BatPayRec extends CCBLifeICBC02Base implements IBatPayRec {
	public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
		RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_req1988.reqHeader);
		retAts.reqSeqID = p_req1988.reqBatchNO;
		
		try {
			CCBLifeICBC02Header tmpBankHeader = new CCBLifeICBC02Header();
			tmpBankHeader.packageID = p_req1988.reqBatchNO;
			tmpBankHeader.fSeqNo = p_req1988.reqBatchNO;
			
			boolean hasOtherBk = p_req1988.hasOtherBank();// 是否存在跨行
			boolean isSameSpd = p_req1988.isSamePaySpd();// 普通加急标志是否都一样
			tmpBankHeader.transCode = "PAYENT";// 批付，非财务室，即普通单笔调用的
			XmlTextWriter xmlWriter = new XmlTextWriter();// 发银行报文的XML对象
			writeCommonHeader(xmlWriter, tmpBankHeader);
			xmlWriter.writeElementString("OnlBatF", "1");
			if (hasOtherBk || !isSameSpd) {
				xmlWriter.writeElementString("SettleMode", "0");
			} else {
				String settleMode1988 = getBankConfig().getValueAsString("settleMode1988");
				if (StringHelper.isNullOrEmpty(settleMode1988)) {
					settleMode1988 = "2";
				}
				xmlWriter.writeElementString("SettleMode", settleMode1988);
			}
			xmlWriter.writeElementString("TotalNum", p_req1988.totalNum);
			xmlWriter.writeElementString("TotalAmt", StringHelper.amountMultiply100(p_req1988.totalAmt));

			Date tmpDateNow = new Date();
			String dateStr = Format.DateTime17Format.format(tmpDateNow);
			String testDate = getBankConfig().getValueAsString("testDate");
			if (testDate != null && !"".equals(testDate)) {
				dateStr = testDate + dateStr.substring(8, 17);
				String passHour = getBankConfig().getValueAsString("passHours");
				String passMiniue = getBankConfig().getValueAsString("passMiniue");
				if (passHour != null && !"".equals(passHour)) {
//					yyyyMMddHHmmssSSS
					Calendar cal = Calendar.getInstance();
					cal.setTime(Format.DateTime17Format.parse(dateStr));
					cal.add(Calendar.HOUR_OF_DAY, Integer.parseInt(passHour));
					cal.add(Calendar.MINUTE,Integer.parseInt(passMiniue));
					dateStr = Format.DateTime17Format.format(cal.getTime());
				}
			}
			xmlWriter.writeElementString("SignTime", dateStr);
//			xmlWriter.writeElementString("SignTime", Format.DateTime17Format.format(tmpDateNow));
			xmlWriter.writeElementString("ReqReserved1", p_req1988.abstractATS);
			xmlWriter.writeElementString("ReqReserved2", p_req1988.reqBatchNO);
			int tmpRdCount = 0;
			while (p_req1988.readRecord()) {
				tmpRdCount++;
				XElement tmpXElement = convertPayRecDetailToBankXElement(p_req1988.readedDetail, tmpRdCount, tmpBankHeader);
				xmlWriter.writeXElement(tmpXElement);
			}
			xmlWriter.writeEndDocument();
			
			String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
			
			if (tmpStrRet[0].length() == 0) {
				StringBuilder tmpSbMsg = new StringBuilder();
				XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
				
				if (tmpBkReader != null) {
					String tmpRetCode = tmpBkReader.getFirstText("/CMS/eb/pub/RetCode");
					String tmpRetMsg = tmpBkReader.getFirstText("/CMS/eb/pub/RetMsg");
					if (!StringHelper.isNullOrEmpty(tmpRetCode)) {
						retAts.respCode = "0";
						retAts.transState = tmpRetCode;
						retAts.respInfo = tmpRetMsg;
						retAts.payInfoCode = tmpRetCode;
						retAts.reqSeqID = tmpBkReader.getFirstText("/CMS/eb/pub/fSeqno");
					} else {
						retAts.respCode = "-1";
						retAts.respInfo = "/CMS/eb/pub/RetCode节点为空";
					}
				} else {
					retAts.respCode = "-1";
					retAts.respInfo = tmpSbMsg.toString();
				}
			} else if (tmpStrRet[0].equals(ConnState.FAIL)) {
				retAts.respCode = "0";
				retAts.respInfo = tmpStrRet[1];
				retAts.reqSeqID = p_req1988.reqBatchNO;
				retAts.transState = PaymentState.FAIL_Batch;
				retAts.payInfoCode = tmpStrRet[0];
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = tmpStrRet[1];
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.toString();
			WriteBankLogLn(ex);
		}
		
		retAts.writeRetToATS();
		return retAts;
	}

	public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
		RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_req9188.reqHeader);
		retAts.reqSeqID = p_req9188.reqBatchNO;

		try {
			CCBLifeICBC02Header tmpBankHeader = new CCBLifeICBC02Header();
			tmpBankHeader.packageID = p_req9188.reqBatchNO;
			tmpBankHeader.fSeqNo = p_req9188.reqBatchNO;
			boolean hasOtherBk = p_req9188.hasOtherBank();
			boolean isSameSpd = p_req9188.isSamePaySpd();
			tmpBankHeader.transCode = "PERDIS";// 批扣个人指令提交

			XmlTextWriter xmlWriter = new XmlTextWriter();
			writeCommonHeader(xmlWriter, tmpBankHeader);
			xmlWriter.writeElementString("OnlBatF", "1");
			if (tmpBankHeader.transCode.equals("PAYPERCOL")) {
				// 批扣个人指令提交汇总记帐
				xmlWriter.writeElementString("BusType", p_req9188.sumAccountFlag);
			} else if ("ENTDIS".equals(tmpBankHeader.transCode)) {
				// 对公批扣只支持逐笔
				xmlWriter.writeElementString("SettleMode", "0");
			} else {
				if (hasOtherBk || !isSameSpd) {
					// 有跨行，或者普通加急标志不一样，只能逐笔入账
					xmlWriter.writeElementString("SettleMode", "0");
				} else {
					String settleMode1988 = getBankConfig().getValueAsString("settleMode9188");
					if (StringHelper.isNullOrEmpty(settleMode1988)) {
						settleMode1988 = "2";
					}
					xmlWriter.writeElementString("SettleMode", settleMode1988);
				}
			}
			xmlWriter.writeElementString("RecAccNo", p_req9188.ownAct);
			xmlWriter.writeElementString("RecAccNameCN", p_req9188.ownActName);
			xmlWriter.writeElementString("RecAccNameEN", "");
			if ("ENTDIS".equals(tmpBankHeader.transCode)) {
				xmlWriter.writeElementString("PayType", "1");
			}
			xmlWriter.writeElementString("TotalNum", p_req9188.totalNum);
			xmlWriter.writeElementString("TotalAmt", StringHelper.amountMultiply100(p_req9188.totalAmt));
			

			Date tmpDateNow = new Date();
			String dateStr = Format.DateTime17Format.format(tmpDateNow);
			String testDate = getBankConfig().getValueAsString("testDate");
			if (testDate != null && !"".equals(testDate)) {
				dateStr = testDate + dateStr.substring(8, 17);
				String passHour = getBankConfig().getValueAsString("passHours");
				String passMiniue = getBankConfig().getValueAsString("passMiniue");
				if (passHour != null && !"".equals(passHour)) {
//					yyyyMMddHHmmssSSS
					Calendar cal = Calendar.getInstance();
					cal.setTime(Format.DateTime17Format.parse(dateStr));
					cal.add(Calendar.HOUR_OF_DAY, Integer.parseInt(passHour));
					cal.add(Calendar.MINUTE,Integer.parseInt(passMiniue));
					dateStr = Format.DateTime17Format.format(cal.getTime());
				}
			}

			xmlWriter.writeElementString("SignTime", dateStr);

			xmlWriter.writeElementString("ReqReserved1", "");
			xmlWriter.writeElementString("ReqReserved2", "");
			int tmpRdCount = 0;
			while (p_req9188.readRecord()) {
				tmpRdCount++;
				XElement tmpXElement = convertRecDetailToBankXElement(p_req9188.readedDetail, tmpRdCount, tmpBankHeader);
				xmlWriter.writeXElement(tmpXElement);
			}
			xmlWriter.writeEndDocument();

			String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());

			if (tmpStrRet[0].length() == 0) {
				StringBuilder tmpSbMsg = new StringBuilder();
				XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);

				if (tmpBkReader != null) {
					String tmpRetCode = tmpBkReader.getFirstText("/CMS/eb/pub/RetCode");
					if (!StringHelper.isNullOrEmpty(tmpRetCode)) {
						retAts.respCode = "0";
						retAts.transState = tmpRetCode;
						retAts.respInfo = tmpRetCode + "-" + tmpBkReader.getFirstText("/CMS/eb/pub/RetMsg");
						retAts.payInfoCode = tmpRetCode;

						String reqSeqID = tmpBkReader.getFirstText("/CMS/eb/pub/fSeqno");
						if (StringHelper.hasAnyChar(reqSeqID)) {
							retAts.reqSeqID = reqSeqID;
						} else {
							retAts.reqSeqID = p_req9188.reqBatchNO;
						}
					} else {
						retAts.respCode = "-1";
						retAts.respInfo = "/CMS/eb/pub/RetCode节点为空";
					}
				} else {
					retAts.respCode = "-1";
					retAts.respInfo = tmpSbMsg.toString();
				}
			} else if (tmpStrRet[0].equals(ConnState.FAIL)) {
				retAts.respCode = "0";
				retAts.respInfo = tmpStrRet[1];
				retAts.reqSeqID = p_req9188.reqBatchNO;
				retAts.transState = PaymentState.FAIL_Batch;
				retAts.payInfoCode = tmpStrRet[0];
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = tmpStrRet[1];
			}

		} catch (Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.toString();
			WriteBankLogLn(ex);
		}

		retAts.writeRetToATS();
		return retAts;
	}

	public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
		RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req1998.reqHeader);
		retAts.reqSeqID = p_req1998.reqBatchNO;
		
		try {
			CCBLifeICBC02Header tmpBankHeader = new CCBLifeICBC02Header();
			tmpBankHeader.transCode = "QPAYENT";
			tmpBankHeader.fSeqNo = p_req1998.reqHeader.transSeqID;
			XmlTextWriter xmlWriter = new XmlTextWriter();
			writeCommonHeader(xmlWriter, tmpBankHeader);
			xmlWriter.writeElementString("QryfSeqno", p_req1998.reqBatchNO);
			xmlWriter.writeElementClosed("QrySerialNo");
			xmlWriter.writeElementClosed("ReqReserved1");
			xmlWriter.writeElementClosed("ReqReserved2");
			xmlWriter.writeEndDocument();

			String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
			
			if (tmpStrRet[0].length() == 0) {
				StringBuilder tmpSbMsg = new StringBuilder();
				XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
				if (tmpBkReader != null) {
					String tmpRetCode = tmpBkReader.getFirstText("/CMS/eb/pub/RetCode");
					String tmpRetMsg = tmpBkReader.getFirstText("/CMS/eb/pub/RetMsg");
					if (!StringHelper.isNullOrEmpty(tmpRetCode)) {
						if (tmpRetCode.equals("0") || tmpRetCode.equals("B0116") || tmpRetCode.equals("00000")) {
							retAts.reqSeqID = tmpBkReader.getFirstText("/CMS/eb/out/QryfSeqno");
							retAts.respCode = "0";
							if (tmpRetCode.equals("B0116")) {
								retAts.respInfo = tmpRetMsg;
								retAts.transState = tmpRetCode;
								retAts.payInfoCode = tmpRetCode;
								if (StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
									retAts.reqSeqID = p_req1998.reqBatchNO;
								}
							}
							retAts.writeBeforeDetail();
							while (tmpBkReader.read("/CMS/eb/out/rd")) {
								RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();

								tmpRetDetail.recName = tmpBkReader.readedXElement.getSingleText("RecAccNameCN");
								tmpRetDetail.recAct = tmpBkReader.readedXElement.getSingleText("RecAccNo");
								tmpRetDetail.payAmount = StringHelper
										.amountDivide100(tmpBkReader.readedXElement.getSingleText("PayAmt"));
								tmpRetDetail.usage = tmpBkReader.readedXElement.getSingleText("UseCN");
								tmpRetDetail.postScript = tmpBkReader.readedXElement.getSingleText("ERPSqn");
								tmpRetDetail.curType = convertCurToATS(
										tmpBkReader.readedXElement.getSingleText("CurrType"));
								tmpRetDetail.result = tmpRetCode + "+"
										+ tmpBkReader.readedXElement.getSingleText("Result");

								tmpRetDetail.payInfoCode = tmpBkReader.readedXElement.getSingleText("instrRetCode");
								if (StringHelper.isNullOrEmpty(tmpRetDetail.payInfoCode)) {
									tmpRetDetail.payInfoCode = tmpBkReader.readedXElement.getSingleText("iRetCode");
								}
								tmpRetDetail.memo = tmpBkReader.readedXElement.getSingleText("instrRetMsg");
								if (StringHelper.isNullOrEmpty(tmpRetDetail.memo)) {
									tmpRetDetail.memo = tmpBkReader.readedXElement.getSingleText("iRetMsg");
								}
								retAts.writeRetDetail(tmpRetDetail);
							}
						} else {
							retAts.respCode = "-1";
							retAts.respInfo = tmpRetMsg;
						}
					} else {
						retAts.respCode = "-1";
						retAts.respInfo = "节点/CMS/eb/pub/RetCode为空";
					}
				} else {
					retAts.respCode = "-1";
					retAts.respInfo = tmpSbMsg.toString();
				}
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = tmpStrRet[1];
			}
		} catch (Exception ex) {
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}
		
		retAts.writeAfterDetail();
		return retAts;
	}

	public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
		RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req9198.reqHeader);
		retAts.reqSeqID = p_req9198.reqBatchNO;

		try {
			CCBLifeICBC02Header tmpBankHeader = new CCBLifeICBC02Header();
			tmpBankHeader.transCode = "QPERDIS";
			tmpBankHeader.fSeqNo = p_req9198.reqHeader.transSeqID;

			XmlTextWriter xmlWriter = new XmlTextWriter();
			writeCommonHeader(xmlWriter, tmpBankHeader);
			xmlWriter.writeElementString("QryfSeqno", p_req9198.reqBatchNO);
			xmlWriter.writeElementClosed("QrySerialNo");
			xmlWriter.writeElementClosed("ReqReserved1");
			xmlWriter.writeElementClosed("ReqReserved2");
			xmlWriter.writeEndDocument();

			String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());

			if (tmpStrRet[0].length() == 0) {
				StringBuilder tmpSbMsg = new StringBuilder();
				XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
				if (tmpBkReader != null) {
					String tmpRetCode = tmpBkReader.getFirstText("/CMS/eb/pub/RetCode");
					String tmpRetMsg = tmpBkReader.getFirstText("/CMS/eb/pub/RetMsg");
					if (!StringHelper.isNullOrEmpty(tmpRetCode)) {
						if (tmpRetCode.equals("0") || tmpRetCode.equals("B0116") || tmpRetCode.equals("00000")
								|| "B0098".equals(tmpRetCode) || "B0097".equals(tmpRetCode)) {
							retAts.reqSeqID = tmpBkReader.getFirstText("/CMS/eb/out/QryfSeqno");
							retAts.respCode = "0";
							if (tmpRetCode.equals("B0116") || "B0098".equals(tmpRetCode)
									|| "B0097".equals(tmpRetCode)) {
								retAts.respInfo = tmpRetMsg;
								retAts.transState = tmpRetCode;
								retAts.payInfoCode = tmpRetCode;
								if (StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
									retAts.reqSeqID = p_req9198.reqBatchNO;
								}
							}
							retAts.writeBeforeDetail();
							while (tmpBkReader.read("/CMS/eb/out/rd")) {
								RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();

								tmpRetDetail.payName = tmpBkReader.readedXElement.getSingleText("PayAccNameCN");
								tmpRetDetail.payAct = tmpBkReader.readedXElement.getSingleText("PayAccNo");
								tmpRetDetail.payAmount = StringHelper
										.amountDivide100(tmpBkReader.readedXElement.getSingleText("PayAmt"));
								tmpRetDetail.usage = tmpBkReader.readedXElement.getSingleText("UseCN");
								tmpRetDetail.postScript = tmpBkReader.readedXElement.getSingleText("ERPSqn");
								tmpRetDetail.curType = convertCurToATS(
										tmpBkReader.readedXElement.getSingleText("CurrType"));
								tmpRetDetail.result = tmpRetCode + "+"
										+ tmpBkReader.readedXElement.getSingleText("Result");
								tmpRetDetail.payInfoCode = tmpBkReader.readedXElement.getSingleText("iRetCode");
								String iRetMsg = tmpBkReader.readedXElement.getSingleTextNotNull("iRetMsg");
								iRetMsg = iRetMsg.length() == 0 ? " " : iRetMsg;
								String BankRem = tmpBkReader.readedXElement.getSingleTextNotNull("BankRem");
								tmpRetDetail.memo = tmpBkReader.readedXElement.getSingleText("iRetCode") + "-" + iRetMsg
										+ "-" + BankRem;

								retAts.writeRetDetail(tmpRetDetail);
							}
						} else {
							retAts.respCode = "-1";
							retAts.respInfo = tmpRetMsg;
						}
					} else {
						retAts.respCode = "-1";
						retAts.respInfo = "节点/CMS/eb/pub/RetCode为空";
					}
				} else {
					retAts.respCode = "-1";
					retAts.respInfo = tmpSbMsg.toString();
				}
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = tmpStrRet[1];
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}

		retAts.writeAfterDetail();
		return retAts;
	}
}
